package com.cw.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.*;
import com.baomidou.mybatisplus.extension.service.impl.*;
import com.cw.entity.*;
import com.cw.mapper.*;
import com.cw.request.*;
import com.cw.response.*;
import com.cw.service.*;
import java.math.*;
import java.util.*;
import java.util.stream.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import org.springframework.util.*;

/**
 * <p>
 * 床位 服务实现类
 * </p>
 *
 * @author smq
 * @since 2021-04-27
 */
@Service
public class BedServiceImpl extends ServiceImpl<BedMapper, Bed> implements IBedService {


    @Autowired
    private IPatientBedService patientBedService;

    @Autowired
    private IPatientInfoService patientInfoService;

    @Autowired
    private IAreaService areaService;

    /**
     * 获取空闲床位
     *
     * @param emptyBedsRequest
     * @return
     */
    @Override
    public Object getEemptyBedsList(EmptyBedsRequest emptyBedsRequest) {
	  Map<String, List<EmptyBedsResponse>> mapList = new HashMap<>();
//	  List<EmptyBedsResponse> responseList = new ArrayList<>();
	  //根据条件获取所有空床信息
	  List<Bed> beds = baseMapper.getEemptyBedsList(emptyBedsRequest);
	  //获取所有院区集合
	  List<String> districtCodes = beds.stream().map(Bed::getDistrictCode).collect(Collectors.toList());
	  if (!CollectionUtils.isEmpty(districtCodes)) {
		for (String districtCode : districtCodes) {
		    //获取所有病区集合
		    List<String> areaList = beds.stream().filter(p -> districtCode.equals(p.getDistrictCode())).map(Bed::getAreaCode).collect(Collectors.toList());
		    if (!CollectionUtils.isEmpty(areaList)) {
			  //根据病区获得床位信息
			  mapList = getEemptyBedsList(mapList, districtCode, areaList);
		    }
		}
	  }

	  return mapList;
    }

    //根据病区获得床位信息
    public Map<String, List<EmptyBedsResponse>> getEemptyBedsList(Map<String, List<EmptyBedsResponse>> mapList, String districtCode,
											List<String> areaCodeList) {
	  List<EmptyBedsResponse> emptyBedsResponseList = new ArrayList<>();
	  String name = "";
	  for (String areaCode : areaCodeList) {
		EmptyBedsResponse emptyBedsResponse = new EmptyBedsResponse();
		//根据院区和病区获取所有病床信息
		List<Bed> beds = baseMapper.selectList(new LambdaQueryWrapper<>(new Bed()).eq(Bed::getDistrictCode, districtCode).eq(Bed::getAreaCode, areaCode)
														  .eq(Bed::getDeleteFlag, "0"));
		if (!CollectionUtils.isEmpty(beds)) {
		    name = beds.get(0).getDistrictName();
		    emptyBedsResponse.setDeptCode(beds.get(0).getDeptCode());
		    emptyBedsResponse.setDeptName(beds.get(0).getDeptName());
		    emptyBedsResponse.setAreaCode(areaCode);
		    emptyBedsResponse.setAreaName(beds.get(0).getAreaName());
		    emptyBedsResponse.setBedsCount(beds.size());
		    emptyBedsResponse.setUsedBedsCount(beds.stream().filter(p -> "1".equals(p.getIsEmptyCode())).collect(Collectors.toList()).size());
		    emptyBedsResponse.setUsedBedsCountDouble(emptyBedsResponse.getUsedBedsCount() != 0 ? new BigDecimal(
			  emptyBedsResponse.getUsedBedsCount() / beds.size()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() : 0);
		    emptyBedsResponse.setEmptyBedsCount(beds.stream().filter(p -> "0".equals(p.getIsEmptyCode())).collect(Collectors.toList()).size());
		    emptyBedsResponse.setUsedBedsCountDouble(emptyBedsResponse.getEmptyBedsCount() != 0 ? new BigDecimal(
			  emptyBedsResponse.getUsedBedsCount() / beds.size()).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() : 0);
		    List<Bed> focusList = beds.stream().filter(p -> "0".equals(p.getBedTypeCode())).collect(Collectors.toList());
		    emptyBedsResponse.setNoFocusManager(beds.stream().filter(p -> "1".equals(p.getBedTypeCode())).collect(Collectors.toList()).size());
		    if (!CollectionUtils.isEmpty(focusList)) {
			  emptyBedsResponse.setFocusManager(focusList.size());
			  //获取床位Id集合
			  List<String> bedIds = focusList.stream().map(Bed::getId).collect(Collectors.toList());
			  //根据床位ids已登记床位
			  List<PatientBed> patientList = patientBedService.getRegisterBedByBedIds(bedIds);
			  if (!CollectionUtils.isEmpty(emptyBedsResponseList)) {
				emptyBedsResponse.setRegisterBedCount(patientList.size());
			  }
		    }

		    //获取房间号集合
		    List<String> roomCodes = beds.stream().map(Bed::getRoomCode).collect(Collectors.toList());
		    if (!CollectionUtils.isEmpty(roomCodes)) {
			  emptyBedsResponse = getManCount(emptyBedsResponse, roomCodes, beds);
		    }
		    emptyBedsResponseList.add(emptyBedsResponse);
		}
		if (StringUtils.isNotEmpty(name) && !CollectionUtils.isEmpty(emptyBedsResponseList)) {
		    mapList.put(name, emptyBedsResponseList);
		}
	  }
	  return mapList;
    }

    public EmptyBedsResponse getManCount(EmptyBedsResponse emptyBedsResponse, List<String> roomCodes, List<Bed> beds) {
	  Integer manCount = 0;
	  Integer womanCount = 0;
	  Integer unknownCount = 0;
	  for (String room : roomCodes) {
		List<Bed> bed = beds.stream().filter(p -> room.equals(p.getRoomCode())).collect(Collectors.toList());
		if (!CollectionUtils.isEmpty(bed)) {
		    //大于三张床的是男女混住
		    //住人的
		    List<Bed> zr = bed.stream().filter(p -> "0".equals(p.getIsEmptyCode())).collect(Collectors.toList());
		    //没住人的
		    List<Bed> mzr = bed.stream().filter(p -> "0".equals(p.getIsEmptyCode())).collect(Collectors.toList());
		    if (bed.size() > 3) {
			  unknownCount = unknownCount + mzr.size();
		    } else {
			  //查看有人住的是男还是女
			  if (!CollectionUtils.isEmpty(zr)) {
				//查看住人的床位患者就诊号
				PatientBed PatientBed = patientBedService.getVisitNo(zr.get(0).getId());
				if (PatientBed != null) {
				    PatientInfo patientInfo = patientInfoService.getPatient(PatientBed.getVisitNo(), PatientBed.getVisitTypeCode());
//				PatientInfo patientInfo = patientInfoService.getPatient(patientBedService.getVisitNo(zr.get(0).getId()));
				    if (patientInfo != null) {
					  //查看住人的床位患者性别
					  if ("1".equals(patientInfo.getSexCode())) {
						manCount = manCount + mzr.size();
					  } else if ("2".equals(patientInfo.getSexCode())) {
						womanCount = womanCount + mzr.size();
					  } else {
						unknownCount = unknownCount + mzr.size();
					  }
				    }

				}
			  }
		    }
		}
	  }
	  emptyBedsResponse.setManEmptyBedsCount(manCount);
	  emptyBedsResponse.setWomanEmptyBedsCount(womanCount);
	  emptyBedsResponse.setUnknownEmptyBedsCount(unknownCount);
	  return emptyBedsResponse;
    }

    /**
     * 获取空闲床位详情
     *
     * @param districtCode
     * @param areaCode
     * @return
     */
    @Override
    public Object getEemptyBedsDetails1(String districtCode, String areaCode) {
//	  Map<String, List<Map<String, List<Bed>>>> bedsDetails = new HashMap<>();
	  List<EmptyBedsDetailResponse> bedsDetails = new ArrayList<>();
	  if (StringUtils.isNotEmpty(areaCode)) {
//		List<Map<String, List<Bed>>> roomMaps = getMapList(districtCode, areaCode);
		EmptyBedsDetailResponse roomMaps = getMapList1(districtCode, areaCode);
		if (roomMaps != null) {
		    bedsDetails.add(roomMaps);
		}
//		if (!CollectionUtils.isEmpty(roomMaps)) {
//		    //根据病区编号获取病区
//		    Area area = areaService.getArea(areaCode);
//		    if (area != null) {
//			  bedsDetails.put(area.getAreaName(), roomMaps);
//		    }
//		}
	  } else {
		//获取院区的所有病区
		List<Bed> beds = baseMapper.selectList(new LambdaQueryWrapper<>(new Bed()).eq(Bed::getDistrictCode, districtCode).eq(Bed::getDeleteFlag, "0"));
		if (!CollectionUtils.isEmpty(beds)) {
		    List<String> areaCodeList = beds.stream().map(Bed::getAreaCode).collect(Collectors.toList());
		    for (String area : areaCodeList) {
//			  List<Map<String, List<Bed>>> roomMaps = getMapList(districtCode, area);
			  EmptyBedsDetailResponse roomMaps = getMapList1(districtCode, area);
			  if (roomMaps != null) {
				bedsDetails.add(roomMaps);
			  }

//			  if (!CollectionUtils.isEmpty(roomMaps)) {
//				//根据病区编号获取病区
//				Area a = areaService.getArea(areaCode);
//				if (area != null) {
//				    bedsDetails.put(a.getAreaName(), roomMaps);
//				}
//			  }
		    }
		}
	  }
	  return bedsDetails;
    }

    public EmptyBedsDetailResponse getMapList1(String districtCode, String areaCode) {
//	  List<Map<String, List<Bed>>> roomMaps = new ArrayList<>();
	  EmptyBedsDetailResponse roomMaps = new EmptyBedsDetailResponse();
	  //根据院区和病区获取所有病床信息
	  List<Bed> beds = baseMapper.selectList(new LambdaQueryWrapper<>(new Bed()).eq(Bed::getDistrictCode, districtCode).eq(Bed::getAreaCode, areaCode)
													    .eq(Bed::getDeleteFlag, "0"));
	  if (!CollectionUtils.isEmpty(beds)) {
		roomMaps.setAreaCode(beds.get(0).getAreaCode());
		roomMaps.setAreaName(beds.get(0).getAreaName());
		roomMaps.setBedsCount(beds.size());
		roomMaps.setEmptyBedsCount(beds.stream().filter(p -> "0".equals(beds.get(0).getIsEmptyCode())).collect(Collectors.toList()).size());
		//根据病床信息获取所有房间号Code
		List<String> roomNameList = beds.stream().map(Bed::getRoomName).collect(Collectors.toList());
		//根据房间号获取病床信息
		for (String roomName : roomNameList) {
		    Map<String, List<Bed>> map = new HashMap<>();
		    List<Bed> b = beds.stream().filter(p -> roomName.equals(p.getRoomName())).sorted(Comparator.comparing(Bed::getBedCode)).collect(
			  Collectors.toList());
		    if (!CollectionUtils.isEmpty(b)) {
			  //获取床位患者信息
			  b = getPatientName(b);
			  map.put(roomName, b);
//			  roomMaps.add(map);
			  roomMaps.setRoomAndBeds(map);
		    }
		}
	  }
	  return roomMaps;
    }


    /**
     * 获取床位患者信息
     *
     * @param bedList
     * @return
     */
    public List<Bed> getPatientName(List<Bed> bedList) {
	  for (Bed bed : bedList) {
		if ("1".equals(bed.getIsEmptyCode())) {
		    PatientBed PatientBed = patientBedService.getVisitNo(bed.getId());
		    if (PatientBed != null) {
			  bed.setIsHisConfirm(PatientBed.getIsHisConfirm());
			  if (StringUtils.isNotEmpty(PatientBed.getVisitNo())) {
				//根据就诊号获取病人姓名
				PatientInfo patientInfo = patientInfoService.getPatient(PatientBed.getVisitNo(), PatientBed.getVisitTypeCode());
				if (patientInfo != null) {
				    bed.setPatientName(patientInfo.getPatientName());
				}
			  }
		    }
		}
	  }
	  return bedList;
    }

    /**
     * 获取空闲床位详情
     *
     * @return
     */
    @Override
    public Object getEemptyBedsDetails(EmptyBedsRequest emptyBedsRequest) {
	  List<EmptyBedsDetailResponse> bedsDetails = new ArrayList<>();
	  //根据条件获取所有空床信息
	  List<Bed> beds = baseMapper.getEemptyBedsList(emptyBedsRequest);
	  if (!CollectionUtils.isEmpty(beds)) {
		//获取病区集合
		List<String> areaCodeList = beds.stream().map(Bed::getAreaCode).collect(Collectors.toList());
		for (String area : areaCodeList) {
//			  List<Map<String, List<Bed>>> roomMaps = getMapList(districtCode, area);
		    EmptyBedsDetailResponse roomMaps = getMapList(emptyBedsRequest.getDistrictCodeList().get(0), area, beds);
		    if (roomMaps != null) {
			  bedsDetails.add(roomMaps);
		    }

//			  if (!CollectionUtils.isEmpty(roomMaps)) {
//				//根据病区编号获取病区
//				Area a = areaService.getArea(areaCode);
//				if (area != null) {
//				    bedsDetails.put(a.getAreaName(), roomMaps);
//				}
//			  }
		}
	  }

	  return bedsDetails;

    }

    public EmptyBedsDetailResponse getMapList(String districtCode, String areaCode, List<Bed> bedList) {
//	  List<Map<String, List<Bed>>> roomMaps = new ArrayList<>();
	  EmptyBedsDetailResponse roomMaps = new EmptyBedsDetailResponse();
	  //根据院区和病区获取所有空床的房间号信息
	  List<String> roomCodeList = bedList.stream().map(Bed::getRoomCode).collect(Collectors.toList());

	  //根据院区和病区和房间号获取所有病床信息
	  List<Bed> beds = baseMapper.selectList(new LambdaQueryWrapper<>(new Bed()).eq(Bed::getDistrictCode, districtCode).eq(Bed::getAreaCode, areaCode)
													    .eq(Bed::getDeleteFlag, "0").in(Bed::getRoomCode, roomCodeList));
	  if (!CollectionUtils.isEmpty(beds)) {
		roomMaps.setDeptCode(beds.get(0).getDeptCode());
		roomMaps.setDeptName(beds.get(0).getDeptName());
		roomMaps.setAreaCode(beds.get(0).getAreaCode());
		roomMaps.setAreaName(beds.get(0).getAreaName());
		roomMaps.setBedsCount(beds.size());
		roomMaps.setEmptyBedsCount(beds.stream().filter(p -> "0".equals(beds.get(0).getIsEmptyCode())).collect(Collectors.toList()).size());
		//根据病床信息获取所有房间号Code
		List<String> roomNameList = beds.stream().map(Bed::getRoomName).collect(Collectors.toList());
		//根据房间号获取病床信息
		for (String roomName : roomNameList) {
		    Map<String, List<Bed>> map = new HashMap<>();
		    List<Bed> b = beds.stream().filter(p -> roomName.equals(p.getRoomName())).sorted(Comparator.comparing(Bed::getBedCode)).collect(
			  Collectors.toList());
		    if (!CollectionUtils.isEmpty(b)) {
			  //获取床位患者信息
			  b = getPatientName(b);
			  map.put(roomName, b);
//			  roomMaps.add(map);
			  roomMaps.setRoomAndBeds(map);
		    }
		}
	  }
	  return roomMaps;
    }

}
